<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间查询">
        <el-date-picker
          v-model="dateRange"
          style="width: 215px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="会员姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入会员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据编号" prop="billNumber">
        <el-input
          v-model="queryParams.billNumber"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品代码" prop="goodCode">
        <el-input
          v-model="queryParams.goodCode"
          placeholder="请输入商品代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodName">
        <el-input
          v-model="queryParams.goodName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存类型" prop="stockType">
        <el-select v-model="queryParams.stockType" placeholder="请选择库存类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="团队查询" prop="deptId">
        <treeselect style="width: 215px" v-model="queryParams.deptId" :options="deptOptions" :show-count="true"
                    placeholder="请选择团队"/>
      </el-form-item>
      <el-form-item label="库存描述" prop="stockDesc">
        <el-input
          v-model="queryParams.stockDesc"
          placeholder="请输入库存描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:inventoryRecord:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['data:inventoryRecord:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['data:inventoryRecord:remove']"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['data:inventoryRecord:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe border v-loading="loading" :data="inventoryRecordList" @selection-change="handleSelectionChange"
              @sort-change="tableSortChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="id" v-if="false"/>
      <el-table-column label="会员姓名" align="center" prop="nickName"/>
      <el-table-column label="单据编号" align="center" prop="billNumber" min-width="100"/>
      <el-table-column label="商品代码" align="center" prop="goodCode"/>
      <el-table-column label="商品名称" align="center" prop="goodName"/>
      <el-table-column label="增加数量" align="center" prop="inAmount"/>
      <el-table-column label="减少数量" align="center" prop="outAmount"/>
      <el-table-column label="库存类型" align="center" prop="stockType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_type" :value="scope.row.stockType"/>
        </template>
      </el-table-column>
      <el-table-column label="库存描述" align="center" prop="stockDesc" min-width="400" show-overflow-tooltip/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" :sortable="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            size="small"-->
      <!--            type="primary"-->
      <!--            plain-->
      <!--            icon="el-icon-edit"-->
      <!--            @click="handleUpdate(scope.row)"-->
      <!--            v-hasPermi="['data:inventoryRecord:edit']"-->
      <!--          >修改-->
      <!--          </el-button>-->
      <!--          <el-button-->
      <!--            size="small"-->
      <!--            type="danger"-->
      <!--            plain-->
      <!--            icon="el-icon-delete"-->
      <!--            @click="handleDelete(scope.row)"-->
      <!--            v-hasPermi="['data:inventoryRecord:remove']"-->
      <!--          >删除-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-col :span="12">
            <el-form-item label="单据编号" prop="billNumber">
              <el-input v-model="form.billNumber" readonly placeholder="系统自动生成"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员姓名" prop="nickName">
              <el-input placeholder="请选择会员" v-model="form.nickName" readonly
                        class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="showUserList"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品信息" prop="goodId">
              <el-input placeholder="请选择商品" v-model="form.goodName" readonly
                        class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="showGoodList"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存类型" prop="stockType">
              <el-select v-model="form.stockType" placeholder="请选择库存类型">
                <el-option
                  v-for="dict in dict.type.sys_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="库存描述" prop="stockDesc">-->
          <!--              <el-input type="textarea" :rows="4" v-model="form.stockDesc" placeholder="请输入库存描述"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 会员列表 -->
    <el-dialog title="会员列表" :visible.sync="userOpen" width="800px" append-to-body>
      <el-form :model="queryUserParams" ref="queryUserForm" size="small" :inline="true"
               label-width="68px">
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryUserParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="会员级别" prop="userLevel">
          <el-select
            v-model="queryUserParams.userLevel"
            placeholder="会员级别"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.user_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table stripe border v-loading="userLoading" :data="userList">
        <el-table-column label="会员编号" align="center" key="userId" prop="userId"/>
        <el-table-column label="登录账号" align="center" key="userName" prop="userName"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="会员姓名" align="center" key="nickName" prop="nickName"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber"
                         width="120"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              plain
              icon="el-icon-edit"
              @click="selectUser(scope.row)"
              v-hasPermi="['system:user:edit']"
            >选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="userTotal>0"
        :total="userTotal"
        :page.sync="queryUserParams.pageNum"
        :limit.sync="queryUserParams.pageSize"
        @pagination="getUserList"
      />
    </el-dialog>

    <!-- 商品列表 -->
    <el-dialog title="商品列表" :visible.sync="goodOpen" width="800px" append-to-body>
      <el-form :model="queryGoodParams" ref="queryGoodForm" size="small" :inline="true"
               label-width="68px">
        <el-form-item>
          <el-button type="error" icon="el-icon-delete" size="mini" @click="closeGood">关闭</el-button>
        </el-form-item>
      </el-form>
      <el-table stripe border v-loading="goodLoading" :data="goodList">
        <el-table-column label="商品主键" align="center" prop="id" v-if="false"/>
        <el-table-column label="商品图片" align="center" prop="goodImg" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.goodImg" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="商品代码" align="center" prop="goodCode"/>
        <el-table-column label="商品名称" align="center" prop="goodName"/>
        <el-table-column label="计量单位" align="center" prop="unitName"/>
        <el-table-column label="商品规格" align="center" prop="standard"/>
        <el-table-column label="金豆个数" align="center" prop="goldBean"/>
        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              plain
              icon="el-icon-edit"
              @click="selectGood(scope.row)"
              v-hasPermi="['data:inventoryRecord:edit']"
            >添加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="goodTotal>0"
        :total="goodTotal"
        :page.sync="queryGoodParams.pageNum"
        :limit.sync="queryGoodParams.pageSize"
        @pagination="getGoodList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  addInventoryRecord,
  delInventoryRecord,
  getInventoryRecord,
  listInventoryRecord,
  updateInventoryRecord
} from "@/api/data/inventoryRecord";
import {deptTreeSelect, listStockUser} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {parseTime} from "@/utils/ruoyi";
import {listGood} from "@/api/base/good";

export default {
  name: "InventoryRecord",
  dicts: ['sys_type'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 会员遮罩层
      userLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员总条数
      userTotal: 0,
      // 库存记录表格数据
      inventoryRecordList: [],
      // 会员表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示会员弹出层
      userOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: null,
        isAsc: null,
        deptId: null,
        userId: null,
        nickName: null,
        billNumber: null,
        goodId: null,
        goodCode: null,
        goodName: null,
        amount: null,
        inAmount: null,
        outAmount: null,
        stockType: null,
        stockDesc: null,
      },
      // 会员查询参数
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        status: 0,
        phonenumber: undefined,
        userLevel: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          {required: true, message: "请选择会员", trigger: "blur"}
        ],
        goodId: [
          {required: true, message: "请选择商品", trigger: "blur"}
        ],
        amount: [
          {required: true, message: "请输入金额", trigger: "blur"}
        ],
        stockType: [
          {required: true, message: "请选择库存类型", trigger: "blur"}
        ],
      },
      // 商品遮罩层
      goodLoading: true,
      // 商品总条数
      goodTotal: 0,
      // 商品表格数据
      goodList: [],
      // 是否显示商品弹出层
      goodOpen: false,
      // 商品查询参数
      queryGoodParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 代理树选项
      deptOptions: undefined,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 182);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一整年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 日期范围
      dateRange: [parseTime(new Date().setDate(1), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')],
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询代理下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 显示会员列表 */
    showUserList() {
      this.resetUserQuery()
      this.userOpen = true
      this.getUserList()
    },
    /** 会员列表 */
    getUserList() {
      this.userLoading = true;
      listStockUser(this.queryUserParams).then(response => {
          this.userList = response.rows;
          this.userTotal = response.total;
          this.userLoading = false;
        }
      );
    },
    /** 搜索会员按钮操作 */
    handleUserQuery() {
      this.queryUserParams.pageNum = 1;
      this.userList = [];
      this.userTotal = 0;
      this.getUserList();
    },
    /** 重置会员按钮操作 */
    resetUserQuery() {
      this.resetForm("queryUserForm");
      this.handleUserQuery();
    },
    /** 选择会员 */
    selectUser(row) {
      this.form.deptId = row.deptId
      this.form.userId = row.userId
      this.form.nickName = row.nickName
      this.userOpen = false
    },
    /** 显示商品列表 */
    showGoodList() {
      this.resetGoodQuery()
      this.goodOpen = true
      this.getGoodList()
    },
    /** 商品列表 */
    getGoodList() {
      this.goodLoading = true;
      listGood(this.queryGoodParams).then(response => {
          this.goodList = response.rows;
          this.goodTotal = response.total;
          this.goodLoading = false;
        }
      );
    },
    /** 搜索商品按钮操作 */
    handleGoodQuery() {
      this.queryGoodParams.pageNum = 1;
      this.goodList = [];
      this.goodTotal = 0;
      this.getGoodList();
    },
    /** 重置商品按钮操作 */
    resetGoodQuery() {
      this.resetForm("queryGoodForm");
      this.handleGoodQuery();
    },
    /** 选择商品 */
    selectGood(row) {
      this.form.goodId = row.id
      this.form.goodCode = row.goodCode
      this.form.goodName = row.goodName
      this.goodOpen = false
    },
    /** 选择商品 */
    closeGood() {
      this.goodOpen = false
    },
    /** 查询库存记录列表 */
    getList() {
      this.loading = true;
      listInventoryRecord(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.inventoryRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        userId: null,
        nickName: null,
        billNumber: null,
        goodId: null,
        goodCode: null,
        goodName: null,
        amount: null,
        inAmount: null,
        outAmount: null,
        stockType: null,
        stockDesc: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [parseTime(new Date().setDate(1), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')]
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 通用排序 */
    tableSortChange(column) {
      this.queryParams.pageNum = 1
      if (column.order === 'descending') {
        this.queryParams.orderByColumn = column.prop
        this.queryParams.isAsc = 'desc'
      } else if (column.order === 'ascending') {
        this.queryParams.orderByColumn = column.prop
        this.queryParams.isAsc = 'asc'
      } else {
        this.queryParams.orderByColumn = undefined
        this.queryParams.isAsc = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInventoryRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInventoryRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventoryRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存记录编号为"' + ids + '"的数据项？').then(function () {
        return delInventoryRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('data/inventoryRecord/export', {
        ...this.queryParams
      }, `inventoryRecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
